package org.kits.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author SKyOne
 * @create 2020-03-08 19:22
 */
@Service
public class RedisDemoService {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 简单限流
     * @param userId
     * @param actionKey
     * @param period
     * @param maxCount
     * @return
     */
    public boolean isActionAllowed(String userId, String actionKey, int period, int maxCount) {
        String key = String.format("hist:%s:%s", userId, actionKey);
        System.out.println("key=>" + key);
        long nowTs = System.currentTimeMillis();
        System.out.println("nowTs=>" + nowTs);

        List<Object> resultList = redisTemplate.executePipelined(new RedisCallback<Object>() {

            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                // 2.connection 打开管道
                connection.openPipeline();
                connection.multi();

                // 3.connection 给本次管道内添加 要一次性执行的多条命令

                // 3.1 一个set操作
                connection.zAdd(key.getBytes(), nowTs, new String(nowTs + "").getBytes());
                connection.zRemRangeByScore(key.getBytes(), 0, nowTs - period * 1000);
                connection.zCard(key.getBytes());
                connection.expire(key.getBytes(), period + 1);
                connection.exec();

                return null;
            }
        });

        System.out.println("resultList=>" + JSONObject.toJSONString(resultList));

        return true;
    }


}
